package com.mall.web.controller;

/**
 * @author ycs
 *2016年7月20日09:59:26
 *支付宝相关操作
 */

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.WebUtils;

import com.mall.pay.alipay.util.AlipayNotify;
import com.mall.pay.alipay.util.AlipaySubmit;
import com.mall.untils.HttpClientUtil;
import com.mall.untils.MapUtil;
import com.mall.untils.PropertiesUtil;
import com.mall.web.service.ALiPayService;

@Controller
@RequestMapping(value = "/aLiPay")
public class ALiPayController{
	
	private Logger logger = LoggerFactory.getLogger(ALiPayController.class);
	
	@Resource ALiPayService aLiPayService;
	
	/**
     * pc端调用支付宝生成二维码页面
     *
     */
	@RequestMapping(value = "/codePage")
	public  void codePage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
			Map<String,Object> paraMap = WebUtils.getParametersStartingWith(request, "");						
			  
			String platformType=MapUtil.getStringValue(paraMap, "platformType");								//平台类型	
			String orderType=MapUtil.getStringValue(paraMap, "orderType");										//平台订单类型
		 	String WIDout_trade_no=MapUtil.getStringValue(paraMap, "WIDout_trade_no");							//订单编号
	        String WIDsubject=MapUtil.getStringValue(paraMap, "WIDsubject");									//订单名称
	        String WIDtotal_fee=MapUtil.getStringValue(paraMap, "WIDtotal_fee");								//订单金额
	        String WIDbody=MapUtil.getStringValue(paraMap, "WIDbody");											//订单描述,对其进行处理	       
	        String WIDshow_url=MapUtil.getStringValue(paraMap, "WIDshow_url");									//商品地址
	        String payUrl="toALiPay";																			//支付地址
	        	        
	        StringBuffer sbHtml = aLiPayService.getAliPayHtml(payUrl,platformType,orderType,WIDout_trade_no,WIDsubject,WIDtotal_fee,WIDbody,WIDshow_url);
	        String sHtmlText= sbHtml.toString();
	        aLiPayService.outputStream(request,response,sHtmlText);		
	}
	
	/**
     * pc端二维码支付，快捷支付
     *
     */		
	@RequestMapping("/toALiPay")
	public void toEditAuction(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
				Map<String,Object> paraMap = WebUtils.getParametersStartingWith(request, "");
				
				//商户订单号,商户网站订单系统中唯一订单号
				String out_trade_no = MapUtil.getStringValue(paraMap, "WIDout_trade_no");
				//订单名称
				String subject = MapUtil.getStringValue(paraMap, "WIDsubject");
				//付款金额
				String total_fee = MapUtil.getStringValue(paraMap, "WIDtotal_fee");
				//订单描述
				String body = MapUtil.getStringValue(paraMap, "WIDbody");	
				//商品展示地址
				String show_url = MapUtil.getStringValue(paraMap, "WIDshow_url");
				
				//支付类型
				String payment_type = "1";
				
				//需以http://开头的完整路径，例如：http://www.商户网址.com/myorder.html,防钓鱼时间戳，未设置不用填
				String anti_phishing_key = "";
				//若要使用请调用类文件submit中的query_timestamp函数，客户端的IP地址，可以不用填
				String exter_invoke_ip = "";
				
				//支付请求的平台
				String platformType=MapUtil.getStringValue(paraMap, "platformType");
				//支付请求的平台订单类型
				String orderType=MapUtil.getStringValue(paraMap, "orderType");
				

				//服务器通知页面路径,需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/			
				String notify_url =PropertiesUtil.getALiPayProperties("notify_url");
				String return_url =PropertiesUtil.getALiPayProperties("return_url");
								
				//把请求参数打包成数组
				Map<String, String> sParaTemp = new HashMap<String, String>();
				sParaTemp.put("service", "create_direct_pay_by_user");
		        sParaTemp.put("partner", PropertiesUtil.getALiPayProperties("partner"));
		        sParaTemp.put("seller_email", PropertiesUtil.getALiPayProperties("seller_email"));
		        sParaTemp.put("_input_charset", PropertiesUtil.getALiPayProperties("input_charset"));
				sParaTemp.put("payment_type", payment_type);
				sParaTemp.put("notify_url", notify_url);
				sParaTemp.put("return_url", return_url);
				sParaTemp.put("out_trade_no", out_trade_no);
				sParaTemp.put("subject", subject);
				sParaTemp.put("total_fee", total_fee);
				sParaTemp.put("body", body);
				sParaTemp.put("show_url", show_url);
				sParaTemp.put("anti_phishing_key", anti_phishing_key);
				sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
				sParaTemp.put("extra_common_param", platformType+"-"+orderType);
				
				//建立请求
				String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"post","确认");
				logger.info("支付宝pc端提交的具体页面："+sHtmlText);
                aLiPayService.outputStream(request,response,sHtmlText);	
	}
	
	/**
	 * pc端支付宝异步回调
	 * 
	 */	
	@RequestMapping("/notifyUrl")
	public void notifyUrl(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.info("【pc端通知开始】");
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		
		String trade_status = params.get("trade_status") == null ? "" : params.get("trade_status");	
		boolean verify_result = AlipayNotify.verify(params);
		logger.info("【pc端支付宝日志记录】======"+params);	
		logger.info("【pc端支付宝异步回调verify_result值：】======"+verify_result);	
		if(verify_result){//验证成功
			//请在这里加上商户的业务逻辑程序代码
			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){			
				aLiPayService.addRecord(params,12);
							
				logger.info("【pc端通知回调结束】======"+params);
				Writer write = resp.getWriter();
				write.write("success");
				write.flush();
				write.close();
			} 
		}
	}
	
	/**
	 * pc端支付宝同步回调
	 * 
	 */	
	@RequestMapping("/returnUrl")
	public void returnUrl(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号
		String trade_status = params.get("trade_status") == null ?"":params.get("trade_status");
		
		boolean verify_result = AlipayNotify.verify(params);
		logger.info("【pc端支付宝同步回调verify_result值：】======"+verify_result);
		if(verify_result){//验证成功
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序	
				
				String extra_common_param =MapUtil.getStringValue(params, "extra_common_param");
				String platform_type=extra_common_param.split("-")[0];
				String orderType=extra_common_param.split("-")[1];				
				String out_trade_no=MapUtil.getStringValue(params, "out_trade_no");
				Map<String, Object> configMap=aLiPayService.getCodeurl(platform_type, "12");
				String notify_url=MapUtil.getStringValue(configMap, "notify_url");	
				List<NameValuePair> param=new ArrayList<NameValuePair>();
				param.add(new BasicNameValuePair("orderId",out_trade_no));
				param.add(new BasicNameValuePair("orderType",orderType));
				param.add(new BasicNameValuePair("type","success"));

				String return_url=HttpClientUtil.post(notify_url, param);
				System.out.println("PC端post返回参数"+return_url);	
				response.setContentType("text/html;charset=utf-8");
				response.setCharacterEncoding("utf-8");
				StringBuffer sb= new StringBuffer();
				sb.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
				sb.append("window.location.href='"+return_url+"';");
				sb.append("</script>");
				Writer write = response.getWriter();
				write.write(sb.toString());
				write.flush();

			}
		}else{
			//该页面可做页面美工编辑
			System.out.println("PC端验证失败");
		}
	}
	
	
	
	/**
     * 手机端端调用支付宝生成页面
     *
     */
	@RequestMapping(value = "/mobileCodePage")
	public  void appCodePage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
			Map<String,Object> paraMap = WebUtils.getParametersStartingWith(request, "");
			
			String orderType=MapUtil.getStringValue(paraMap, "orderType");										//平台订单类型	
		 	String WIDout_trade_no=MapUtil.getStringValue(paraMap, "WIDout_trade_no");							//订单编号
	        String WIDsubject=MapUtil.getStringValue(paraMap, "WIDsubject");									//订单名称
	        String WIDtotal_fee=MapUtil.getStringValue(paraMap, "WIDtotal_fee");								//订单金额
	        String WIDbody=MapUtil.getStringValue(paraMap, "WIDbody");											//内容是平台类型       
	        String WIDshow_url=MapUtil.getStringValue(paraMap, "WIDshow_url");									//商品地址
	        String payUrl="toMobileALiPay";																		//支付地址
	             
	        StringBuffer sbHtml = aLiPayService.getAliPayHtml(payUrl,WIDbody,orderType,WIDout_trade_no,WIDsubject,WIDtotal_fee,WIDbody,WIDshow_url);
	        String sHtmlText= sbHtml.toString();
	        aLiPayService.outputStream(request,response,sHtmlText);		
	}
	
	/**
     * 手机端调用支付宝页面
     *
     */
	@RequestMapping("/toMobileALiPay")
	public void toAppALiPay(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
				Map<String,Object> paraMap = WebUtils.getParametersStartingWith(request, "");
				
				//商户订单号,商户网站订单系统中唯一订单号
				String out_trade_no = MapUtil.getStringValue(paraMap, "WIDout_trade_no");
				//订单名称
				String subject = MapUtil.getStringValue(paraMap, "WIDsubject");
				//付款金额
				String total_fee = MapUtil.getStringValue(paraMap, "WIDtotal_fee");
				//订单描述,这里用来传递平台类型
				String body = MapUtil.getStringValue(paraMap, "WIDbody");	
				//支付请求的平台订单类型
				String orderType=MapUtil.getStringValue(paraMap, "orderType");
												
				//商品展示地址
				String show_url = MapUtil.getStringValue(paraMap, "WIDshow_url");				
				//支付类型
				String payment_type = "1";
				//服务器通知页面路径,需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/			
				String notify_url = PropertiesUtil.getALiPayProperties("mobileNotifyUrl");
				String return_url = PropertiesUtil.getALiPayProperties("mobileReturnUrl");
				
				//把请求参数打包成数组
				Map<String, String> sParaTemp = new HashMap<String, String>();
				sParaTemp.put("service", "alipay.wap.create.direct.pay.by.user");
		        sParaTemp.put("partner", PropertiesUtil.getALiPayProperties("partner"));
		        sParaTemp.put("seller_id", PropertiesUtil.getALiPayProperties("partner"));
		        sParaTemp.put("_input_charset", PropertiesUtil.getALiPayProperties("input_charset"));
				sParaTemp.put("payment_type", payment_type);
				sParaTemp.put("notify_url", notify_url);
				sParaTemp.put("return_url", return_url);
				sParaTemp.put("out_trade_no", out_trade_no);
				sParaTemp.put("subject", subject);
				sParaTemp.put("total_fee", total_fee);
				sParaTemp.put("body", body+"-"+orderType);
				sParaTemp.put("show_url", show_url);				
				
				//建立请求
				String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"post","确认");
				logger.info("支付宝移动端提交的具体页面："+sHtmlText);
                aLiPayService.outputStream(request,response,sHtmlText);	
	}
	
	/**
	 * 移动端支付宝异步回调
	 * 
	 */	
	@RequestMapping("/mobileNotifyUrl")
	public void mobileNotifyUrl(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.info("【支付宝移动端 通知开始】");
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		
		String trade_status = params.get("trade_status") == null ? "" : params.get("trade_status");	
		boolean verify_result = AlipayNotify.verify(params);
		logger.info("【移动端支付宝日志记录】======"+params);	
		logger.info("【移动端支付宝异步回调verify_result值：】======"+verify_result);	
		if(verify_result){//验证成功
			//请在这里加上商户的业务逻辑程序代码
			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){			
				aLiPayService.addRecord(params,11);	
						
				logger.info("【移动端通知回调结束】======"+params);
				Writer write = resp.getWriter();
				write.write("success");
				write.flush();
				write.close();
			} 
		}
	}
	
	/**
	 * 移动端支付宝同步回调
	 * 
	 */	
	@RequestMapping("/mobileReturnUrl")
	public void mobileReturnUrl(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号
		String trade_status = params.get("trade_status") == null ?"":params.get("trade_status");
		
		boolean verify_result = AlipayNotify.verify(params);
		logger.info("【移动端支付宝同步回调verify_result值：】======"+verify_result);
		if(verify_result){//验证成功
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序	
				
				//执行异步通知客户端去处理订单
				String body =MapUtil.getStringValue(params, "body");
				String platform_type=body.split("-")[0];
				String orderType=body.split("-")[1];
				String out_trade_no=MapUtil.getStringValue(params, "out_trade_no");
				Map<String, Object> configMap=aLiPayService.getCodeurl(platform_type, "11");
				String notify_url=MapUtil.getStringValue(configMap, "notify_url");				
				List<NameValuePair> param=new ArrayList<NameValuePair>();
				param.add(new BasicNameValuePair("orderId",out_trade_no));
				param.add(new BasicNameValuePair("orderType",orderType));
				param.add(new BasicNameValuePair("type","success"));
				
				String return_url=HttpClientUtil.post(notify_url, param);	
				System.out.println("支付宝移动端返回地址"+return_url);			
				response.setContentType("text/html;charset=utf-8");
				response.setCharacterEncoding("utf-8");
				StringBuffer sb= new StringBuffer();
				sb.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
				sb.append("window.location.href='"+return_url+"';");
				sb.append("</script>");
				Writer write = response.getWriter();
				write.write(sb.toString());
				write.flush();
				write.close();
				
			}
		}else{
			//该页面可做页面美工编辑
			System.out.println("移动端支付宝验证失败");
		}
	}
	
	

	
}

